<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons')
export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    optionData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      chart: null,
      loading: false,
      isZoom: false
    }
  },
  watch: {
    optionData: {
      handler(val) {
        this.isZoom = (val !== undefined && val !== null && val.length > 15)
        this.initChart()
      }
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  mounted() {
    if (this.optionData) {
      this.initChart()
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, null)
      var option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {
          feature: {
            // dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        legend: {
          data: [this.optionData.titleZ, this.optionData.titleX]
        },
        xAxis: [
          {
            type: 'category',
            data: this.optionData.optionsArr,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: this.optionData.leftName,
            min: 0,
            max: Math.max(...this.optionData.dataZ),
            interval: Math.ceil(Math.max(...this.optionData.dataZ) / this.optionData.dataZ.length),
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: this.optionData.rightName,
            min: 0,
            max: Math.max(...this.optionData.dataX),
            interval: Math.ceil(Math.max(...this.optionData.dataX) / this.optionData.dataX.length),
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: this.optionData.titleZ,
            type: 'bar',
            barWidth: '36px',
            data: this.optionData.dataZ
          },
          {
            name: this.optionData.titleX,
            type: 'line',
            yAxisIndex: 1,
            data: this.optionData.dataX
          }
        ]
      }
      this.chart.setOption(option)
    }
  }
}
</script>
